#include "library2/libdb.h"
#include "gtest/gtest.h"
#include <time.h>
#include <memory>

using namespace std;
using namespace basic::library2;

CConnection *g_poDb;
TEST(TestDBCache, InitDBEnv) {
	g_poDb = C_DB_FACTORY->GetDBConnect("mysql");
	g_poDb->InitDB("192.168.0.31", "ticket" , "ticket", "test", 33306, "", 0);
	g_poDb->ExecSQL("drop table if exists db_test");
	g_poDb->ExecSQL("CREATE  TABLE IF NOT EXISTS db_test  ( t1 INT,t2 varchar(255) ) ENGINE innodb;");
}

TEST(TestDBCache, InsertTest) {
	g_poDb->ExecSQL("insert into db_test values(1,'111111'); ");
	g_poDb->ExecSQL("insert into db_test values(2,'2222222'); ");
	g_poDb->ExecSQL("insert into db_test values(3,'33333333'); ");
	g_poDb->ExecSQL("insert into db_test values(4,'444444444'); ");
	auto_ptr<CResultSet> pResult( g_poDb->Query("select * from db_test") );
	EXPECT_EQ(pResult->GetRecordCount(), 4);
}

TEST(TestDBCache, UpdateTest) {
	g_poDb->ExecSQL("update db_test set t1 = 5, t2 = '666666666' where t1=1 ");
	EXPECT_EQ(g_poDb->AffectRow() , 1);
}

TEST(TestDBCache, SelectTest) {
	auto_ptr<CResultSet> pResult( g_poDb->Query("select t2 from db_test where t1=5") );
	EXPECT_EQ(pResult->GetRecordCount(), 1);
    if (pResult->GetRecordCount() >0)
    {
        if (pResult->Next())
		{
			const char *psRsult = pResult->GetField((apr_uint32_t)0);
			EXPECT_STREQ(psRsult, "666666666");
		}
    }
}

TEST(TestDBCache, TranscationTest) 
{
	CConnection *poAnotherDb = C_DB_FACTORY->GetDBConnect("mysql");
	poAnotherDb->InitDB("192.168.0.31", "ticket" , "ticket", "test", 33306, "", 0);

	auto_ptr<CTranscation> pTran(poAnotherDb->createTranscation());
	pTran->Begin();
	poAnotherDb->ExecSQL("update db_test set t1 = 7, t2 = '99999' where t1=2 ");

	auto_ptr<CResultSet> pResult( g_poDb->Query("select t2 from db_test where t1=2") );
	EXPECT_EQ(pResult->GetRecordCount(), 1);
	if (pResult->Next())
	{
		const char *psRsult = pResult->GetField((apr_uint32_t)0);
		EXPECT_STREQ(psRsult, "2222222");
	}

	auto_ptr<CResultSet> pResult2( poAnotherDb->Query("select t2 from db_test where t1=2") );
	EXPECT_EQ(pResult2->GetRecordCount(), 0);

	pTran->Commit();

	auto_ptr<CResultSet> pResult3( g_poDb->Query("select t2 from db_test where t1=2") );
	EXPECT_EQ(pResult3->GetRecordCount(), 0);

}


